package main

import (
	"fmt"
	"strings"
)

/*
19_中介模式
概念：用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要显式地相互引用，从而使其耦合松散，而且可以独立地改变它们之间的交互。
*/

type CDDriver struct {
	Data string
}

func (c *CDDriver) ReadData() {
	fmt.Println("CD驱动器正在读取：", c.Data)
}

type CPUDriver struct {
	Video string
	Sound string
}

func (d *CPUDriver) Process(data string) {
	sp := strings.Split(data, ",")
	d.Sound = sp[0]
	d.Video = sp[1]
	fmt.Println("CPU播放：", d.Sound, d.Video)
}

type GPUDriver struct {
	Image string
}

func (g *GPUDriver) display(data string) {
	g.Image = data
	fmt.Println("GPU正在显示图片:", g.Image)
}

// 中介
type Mediator struct {
	CD  *CDDriver
	CPU *CPUDriver
	GPU *GPUDriver
}

var mediator *Mediator

func GetMediatorInstance() *Mediator {
	if mediator == nil {
		mediator = &Mediator{}
	}
	return mediator
}

func (m *Mediator) change(i interface{}) {
	switch inst := i.(type) {
	case *CDDriver:
		m.CD.ReadData()
	case *CPUDriver:
		m.CPU.Process(inst.Sound + "," + inst.Video)
	case *GPUDriver:
		m.GPU.display(inst.Image)
	default:

	}
}

func main() {
	instance := GetMediatorInstance()
	cd := &CDDriver{Data: "movie"}
	cpu := &CPUDriver{
		Video: "视频",
		Sound: "音乐",
	}
	gpu := &GPUDriver{Image: "图片"}
	instance.CD = cd
	instance.CPU = cpu
	instance.GPU = gpu
	instance.change(cd)
	instance.change(cpu)
	instance.change(gpu)
}
